<?php

namespace Liuhelong\LaravelAdmin\Wechat\Actions\WechatOffiaccountMaterial;

use Encore\Admin\Actions\RowAction;
use Illuminate\Http\Request;
use Request as R;
use Illuminate\Database\Eloquent\Model;
use Liuhelong\LaravelAdmin\Wechat\Models\WechatOffiaccountBroadcast;
use Log;

class BroadCast extends RowAction
{
    public $name = '群发';
    private $wechat;
    
    public function __construct(){
        $this->wechat = app('liuhelong_wechat_service');
        parent::__construct();
    }
    
    public function form()
    {
		$this->radio('send_type', '发送模式')->options(['ALL'=>'所有人','TAG'=>'根据tag发送','OPENID'=>'自定义群发'])->rules('required');
		
		$tags = collect($this->wechat->handle('user_tag','list')['tags'])->pluck('name','id')->all();
		$this->select('tag_id', 'TAG')->options($tags)->help('如果根据tag发送，这里选择相应的tag');
		$this->textarea('openids', 'OPENIDS')->help('如果根据openid发送，这里输入openid列表（至少两个用户的 openid），英文逗号分隔');
		
		$this->hidden('media_type')->value(R::get('type'));
		
    }
	
	public function handle(Model $model, Request $request)
    {
		$media_type = ucfirst($request->media_type);
		try{
		    switch($request->send_type){
		        case('ALL'):
		            $res = $this->wechat->handle('broadcasting','send'.$media_type,[$model->getKey(),null]);
		            break;
	            
		        case('TAG'):
		            if(!$request->tag_id){
		                throw new \Exception('请选择tag');
		            }
		            $res = $this->wechat->handle('broadcasting','send'.$media_type,[$model->getKey(),(int)$request->tag_id]);
		            break;
		        
		        case('OPENID'):
		            if(!$request->openids){
		                throw new \Exception('请输入用户openid');
		            }
		            $res = $this->wechat->handle('broadcasting','send'.$media_type,[$model->getKey(),explode(',',$request->openids)]);
		            break;
		        
		    }
		    // 模拟返回结果
		    /*$res = [
	            'errcode' => 0,
                'errmsg' => 'send job submission success',
                'msg_id' => 1000000005,
                'msg_data_id' => 2247483710,
            ];
		    info($res);*/
		    $broadcast = WechatOffiaccountBroadcast::create([
		        'msg_id' =>  $res['msg_id'],
		        'media_type' =>  $request->media_type,
		        'media_id' => $model->getKey(),
		        'send_type' =>  $request->send_type,
		        'msg_status' =>  '',
    	        'has_send'=> 1
	        ]);
	        // 1分钟以后查询群发状态并更新到数据库-- 弃用 群发成功会收到事件推送，直接通过推送事件处理
			/*HandleBroadcastStatus::dispatch($broadcast)
                ->delay(now()->addMinutes(1));*/
					
			return $this->response()->success('开始群发！')->redirect(route('wechat-o-broadcasts.index'));
		}catch(\Exception $e){
		    Log::error($e);
			return $this->response()->error($e->getMessage())->refresh();
		}
    }
    
}